<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useExamResultStore } from '../stores/examResult'
import { ElContainer, ElHeader, ElMain, ElCard, ElRow, ElCol, ElButton, ElProgress, ElTable, ElTableColumn, ElMessageBox } from 'element-plus'

// ==================== 数据定义 ====================
const router = useRouter()
const examResultStore = useExamResultStore()

// 历次考试记录
const examHistory = ref([])


// ==================== 工具方法 ====================
/**
 * 格式化时间戳为日期时间
 */
const formatTime = (timestamp) => {
  if (!timestamp) return 'N/A'
  return new Date(timestamp).toLocaleString()
}

/**
 * 格式化秒数为时分秒
 */
const formatDuration = (seconds) => {
  if (!seconds) return '0秒'
  
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  
  let result = ''
  if (h > 0) result += `${h}小时`
  if (m > 0) result += `${m}分钟`
  if (s > 0) result += `${s}秒`
  
  return result || '0秒'
}

/**
 * 获取考试类型描述
 */
const getExamTypeDescription = (examType, chapter) => {
  switch (examType) {
    case 'exam':
      return '正式考试'
    case 'chapter':
      return `章节练习 ${chapter} 章`
    case 'random':
      return '随机练习'
    default:
      return '正式考试'
  }
}

// ==================== 页面导航 ====================
/**
 * 返回首页
 */
const goHome = () => {
  // 清除结果数据
  examResultStore.clearResult()
  router.push('/')
}

// ==================== 数据操作 ====================
/**
 * 清除历史记录
 */
const clearHistory = () => {
  ElMessageBox.confirm(
    '确定要清除所有考试历史记录吗？',
    '确认清除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    examHistory.value = []
    localStorage.removeItem('examHistory')
  })
  .catch(() => {
    // 用户取消操作
  })
}

/**
 * 删除单条记录
 */
const deleteRecord = (record) => {
  ElMessageBox.confirm(
    '确定要删除这条考试记录吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 从历史记录中移除该条记录
    const index = examHistory.value.findIndex(item => item.id === record.id)
    if (index !== -1) {
      examHistory.value.splice(index, 1)
      // 更新本地存储
      localStorage.setItem('examHistory', JSON.stringify(examHistory.value))
      
      // 如果删除的是随机考试记录，同时删除对应的随机题库
      if (record.examType === 'random' && record.examId) {
        localStorage.removeItem(`randomExam_${record.examId}`);
      }
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}

/**
 * 获取历史记录（这里模拟从本地存储获取历史记录）
 */
const loadExamHistory = () => {
  const history = localStorage.getItem('examHistory')
  if (history) {
    try {
      examHistory.value = JSON.parse(history)
    } catch (e) {
      console.error('解析历史记录失败:', e);
      examHistory.value = []
    }
  }
}

// ==================== 详情查看 ====================
/**
 * 显示考试详情
 */
const showDetail = (record) => {
  // 生成唯一的会话ID用于查看历史记录，格式与ExamPage.vue中一致
  const sessionId = `review_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  // 保存考试记录到localStorage，供ExamPage.vue使用
  const examRecord = {
    sessionId: sessionId,
    timestamp: Date.now(),
    questions: record.questions.map(q => ({
      id: q.number,
      number: q.number,
      // 根据题目数量分布确定题目类型（简化处理）
      type: q.number <= Math.floor(record.totalQuestions * 0.7) ? 1 : 
            q.number <= Math.floor(record.totalQuestions * 0.8) ? 2 : 3,
      answered: q.answered,
      userAnswer: q.type === 2 ? 
        (Array.isArray(q.userAnswer) ? [...q.userAnswer] : 
         typeof q.userAnswer === 'string' ? q.userAnswer.split(';').map(ans => ans.trim()).filter(ans => ans) : 
         []) : 
        q.type === 3 ?
        (q.userAnswer === 'A' ? '1' : 
         q.userAnswer === 'B' ? '0' : 
         (q.userAnswer !== undefined && q.userAnswer !== null ? String(q.userAnswer) : '')) :
        q.userAnswer
    }))
  }
  
  localStorage.setItem('currentExamRecord', JSON.stringify(examRecord))
  
  // 保存考试信息到localStorage
  const examInfo = {
    examType: record.examType,
    chapter: record.chapter,
    practiceMode: record.examType === 'chapter' ? 'chapter' : (record.examType === 'random' ? 'random' : null),
    examId: record.examId // 随机练习的唯一标识
  }
  
  localStorage.setItem('currentExamInfo', JSON.stringify(examInfo))
  
  // 如果是随机练习，还需要保存题目到localStorage
  if (record.examType === 'random' && record.examId) {
    // 从localStorage获取原始的随机练习题目
    const randomExamDataStr = localStorage.getItem(`randomExam_${record.examId}`);
    if (randomExamDataStr) {
      const randomExamData = JSON.parse(randomExamDataStr);
      // 更新题目中的用户答案
      randomExamData.questions = randomExamData.questions.map(q => {
        const recordQuestion = record.questions.find(rq => rq.number === q.number);
        if (recordQuestion) {
          return {
            ...q,
            answered: recordQuestion.answered,
            userAnswer: recordQuestion.userAnswer
          };
        }
        return q;
      });
      
      // 重新保存到localStorage
      localStorage.setItem(`randomExam_${record.examId}`, JSON.stringify(randomExamData));
    }
  }
  
  // 跳转到考试页面，传递只读模式参数和题目数量参数
  router.push({
    path: '/exam',
    query: {
      readOnly: 'true',
      mode: record.examType === 'exam' ? 'exam' : 'practice',
      practiceMode: record.examType === 'chapter' ? 'chapter' : (record.examType === 'random' ? 'random' : null),
      chapter: record.chapter || 1,
      // 根据历史记录中的题目数量传递参数
      single: record.questions.filter(q => q.typeName === '单选题').length,
      multiple: record.questions.filter(q => q.typeName === '多选题').length,
      trueFalse: record.questions.filter(q => q.typeName === '判断题').length
    }
  })
}

// ==================== 生命周期钩子 ====================
onMounted(() => {
  loadExamHistory()
})
</script>

<template>
  <el-container class="result-container">
    <el-header class="result-header">
      <h1>考试成绩</h1>
    </el-header>
    
    <el-main class="result-main">
      <el-card class="result-card">
        <div class="score-overview">
          <h2>成绩概览</h2>
          <div class="score-circle">
            <el-progress 
              type="circle" 
              :percentage="examResultStore.score" 
              :width="200"
              :stroke-width="12"
              :color="examResultStore.score >= 60 ? '#67c23a' : '#f56c6c'"
              :show-text="false"
            />
            <div class="score-text">
              <span class="score-number">{{ examResultStore.score }}</span>
              <span class="score-label">分</span>
            </div>
          </div>
          
          <div class="score-details">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="detail-item">
                  <div class="detail-value">{{ examResultStore.totalQuestions }}</div>
                  <div class="detail-label">总题数</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="detail-item">
                  <div class="detail-value">{{ examResultStore.answeredQuestions }}</div>
                  <div class="detail-label">已答</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="detail-item">
                  <div class="detail-value">{{ examResultStore.correctAnswers }}</div>
                  <div class="detail-label">正确</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="detail-item">
                  <div class="detail-value">{{ formatDuration(examResultStore.examDuration) }}</div>
                  <div class="detail-label">耗时</div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <div class="exam-time-info">
            <p><strong>开始时间:</strong> {{ formatTime(examResultStore.examStartTime) }}</p>
            <p><strong>结束时间:</strong> {{ formatTime(examResultStore.examEndTime) }}</p>
            <p><strong>考试耗时:</strong> {{ formatDuration(examResultStore.examDuration) }}</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="history-card">
        <div class="history-header">
          <h3>历次考试记录</h3>
          <el-button 
            v-if="examHistory.length > 0" 
            type="danger" 
            size="small" 
            @click="clearHistory"
          >
            清除记录
          </el-button>
        </div>
        <el-table :data="examHistory" class="history-table" stripe>
          <el-table-column prop="date" label="考试时间" min-width="180" />
          <el-table-column prop="examType" label="考试类型" min-width="120">
            <template #default="scope">
              {{ getExamTypeDescription(scope.row.examType, scope.row.chapter) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalQuestions" label="总题数" min-width="80" />
          <el-table-column prop="answeredQuestions" label="答题数" min-width="80" />
          <el-table-column prop="unansweredQuestions" label="未作答数" min-width="100" />
          <el-table-column prop="duration" label="耗时(秒)" min-width="100">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分数" min-width="80">
            <template #default="scope">
              <span :class="scope.row.score >= 60 ? 'pass' : 'fail'">{{ scope.row.score }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="showDetail(scope.row)">
                详情
              </el-button>
              <el-button type="danger" size="small" @click="deleteRecord(scope.row)" style="margin-left: 10px;">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <div class="actions">
        <el-button type="primary" @click="goHome" size="large">返回首页</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<style scoped>
.result-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.result-header {
  background-color: #fff;
  color: #333;
  text-align: center;
  padding: 15px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  flex-shrink: 0;
}

.result-header h1 {
  margin: 0;
  font-size: 24px;
}

.result-main {
  background-color: #f5f5f5;
  padding: 20px;
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-card {
  width: 100%;
  max-width: 1200px;
  margin-bottom: 20px;
}

.history-card {
  width: 100%;
  max-width: 1200px;
  margin-bottom: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-header h3 {
  margin: 0;
  color: #333;
}

.history-table {
  width: 100%;
}

.score-overview h2 {
  text-align: center;
  margin-top: 0;
  color: #333;
}

.score-circle {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 20px auto;
}

.score-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.score-number {
  display: block;
  font-size: 48px;
  font-weight: bold;
  color: #333;
}

.score-label {
  font-size: 16px;
  color: #666;
}

.score-details {
  margin-top: 30px;
}

.detail-item {
  text-align: center;
  padding: 15px 0;
}

.detail-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.detail-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.exam-time-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  text-align: center;
}

.exam-time-info p {
  margin: 5px 0;
  color: #666;
}

.pass {
  color: #67c23a;
  font-weight: bold;
}

.fail {
  color: #f56c6c;
  font-weight: bold;
}

.actions {
  text-align: center;
  margin-top: 20px;
}

/* 考试详情对话框样式 */
.exam-detail-dialog :deep(.el-dialog__body) {
  padding: 0;
  height: 80vh;
}

.exam-info {
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #e4e7ed;
}

.info-item {
  margin-bottom: 10px;
}

.info-item label {
  font-weight: bold;
  color: #666;
}

.info-item span {
  color: #333;
}

/* 考试详情对话框中的考试界面样式 */
.exam-detail-dialog .exam-container {
  height: calc(80vh - 80px);
  width: 100%;
  display: flex;
  flex-direction: column;
}

.exam-detail-dialog .sidebar {
  background-color: #f5f5f5;
  padding: 20px 10px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow-y: auto;
}

.exam-detail-dialog .sidebar h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
  font-size: 16px;
}

.exam-detail-dialog .question-tabs {
  flex: 1;
  height: 100%;
}

.exam-detail-dialog .question-tabs :deep(.el-tabs__header.is-left) {
  margin-right: 10px;
}

.exam-detail-dialog .question-tabs :deep(.el-tabs__content) {
  height: 100%;
}

.exam-detail-dialog .question-tabs :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.exam-detail-dialog .question-tabs :deep(.el-tabs__item) {
  height: auto;
  line-height: normal;
  padding: 10px 15px;
  writing-mode: vertical-lr;
  text-orientation: mixed;
  white-space: nowrap;
  min-width: 30px;
}

.exam-detail-dialog .question-type-info {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
  padding-left: 20px;
}

.exam-detail-dialog .question-list {
  flex: 1;
  margin-bottom: 10px;
  max-height: unset;
  height: 100%;
}

.exam-detail-dialog .question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 5px;
}

.exam-detail-dialog .question-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  font-weight: bold;
  margin: 0 auto;
}

.exam-detail-dialog .question-circle:hover {
  transform: scale(1.1);
}

.exam-detail-dialog .question-circle.active {
  background-color: #409eff;
  color: white;
  border: 2px solid #1a7de0;
}

.exam-detail-dialog .question-circle.answered {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 2px solid #67c23a;
}

.exam-detail-dialog .question-circle.answered.active {
  background-color: #409eff;
  color: white;
  border: 2px solid #1a7de0;
}

.exam-detail-dialog .question-circle.unanswered {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 2px solid #e6a23c;
}

.exam-detail-dialog .legend {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
  margin-top: auto;
}

.exam-detail-dialog .legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 12px;
}

.exam-detail-dialog .legend-color {
  width: 15px;
  height: 15px;
  border-radius: 3px;
  margin-right: 8px;
}

.exam-detail-dialog .answered-color {
  background-color: #f0f9eb;
  border: 1px solid #67c23a;
}

.exam-detail-dialog .unanswered-color {
  background-color: #fdf6ec;
  border: 1px solid #e6a23c;
}

.exam-detail-dialog .active-color {
  background-color: #409eff;
}

.exam-detail-dialog .main-content {
  background-color: #fff;
  padding: 20px;
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  width: 100%;
}

.exam-detail-dialog .question-area {
  width: 100%;
  max-width: 800px;
}

.exam-detail-dialog .question-item h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 20px;
}

.exam-detail-dialog .question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
  align-items: flex-start;
}

.exam-detail-dialog .question-options :deep(.el-radio) {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  height: auto;
  white-space: normal;
  line-height: normal;
  padding: 10px;
}

.exam-detail-dialog .question-options :deep(.el-checkbox) {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  height: auto;
  white-space: normal;
  line-height: normal;
  padding: 10px;
}

.exam-detail-dialog .answer-hint {
  margin-bottom: 20px;
}

.exam-detail-dialog .answer-hint p {
  margin: 5px 0;
}

.exam-detail-dialog .navigation-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
}

.exam-detail-dialog .navigation-buttons :deep(.el-button) {
  width: 100px;
}

.exam-detail-dialog .welcome-message {
  text-align: center;
  padding: 50px 20px;
  width: 100%;
}

.exam-detail-dialog .welcome-message h2 {
  color: #28a745;
  font-size: 32px;
  margin-bottom: 15px;
}
</style>